
import { auditList, updateAudit } from "@/tools/request/api.js"
import JSONBig from 'json-bigint';
 

export default {
	namespaced: true,
	state: () => ({
		firmList: [],
		passedFirmList: [],
		currentFirm: {}
	}),
	mutations: {
		setFirmList (state, value) {
			value.forEach((item) => {
				item.exJson = JSON.parse(item.exJson);
			})
			value.sort((a, b) => {
				if (a.isAudit == 2) {
					return -1;
				}
			})
			value.sort((a, b) => {
				if (a.isDefault == 1) {
					return -1;
				}
			})
			let currentFirm = value.find((item) => {
				return item.isDefault == 1 && item.isAudit == 2;
			})
			if (currentFirm && currentFirm.id) {
				state.currentFirm = currentFirm;
			} else {
				state.currentFirm = [];
			}
			state.firmList = value;
		},
	},
	actions: {
		// 获取所有店铺
		async getFirmList ({dispatch, commit, rootState, state}) {
			let res = await auditList();
			if (res.code != 200) return uni.showMsg();
			let list = res.body;
			if (!list.length) return;
			
			// 将未通过审核的店铺选中状态重置为0
			list.forEach((item) => {
				if (item.isAudit != 2) {
					item.isDefault = 0;
				}
			})
			commit('setFirmList', list);
			
			// 已经通过审核的店铺
			let passFirmList = list.filter((item) => {
				return item.isAudit == 2;
			})
			state.passedFirmList = passFirmList;
			// 当前选中的店铺
			let selected = passFirmList.filter((item) => {
				return item.isDefault == 1;
			})
			if (selected.length < 1 && passFirmList.length > 0) {
				dispatch('updateFirm', passFirmList[0]);
				return;
			}
		},
		
		
		// 切换店铺
		async updateFirm ({commit, dispatch, rootState, state}, item) {
			let postData = {
				id: item.id,
				isDefault: 1,
				adminId: rootState.app_store.adminId,
				userId: rootState.app_store.userId,
				userServiceToken: rootState.app_store.userServiceToken
			}
			// 已选中的店铺
			let selectedFirm = state.passedFirmList.find((item) => {
				return item.isDefault == 1;
			})
			rootState.loading_store.loadingShow = true;
			if (selectedFirm && selectedFirm.id) {
				 // 将之前选中的店铺取消选中状态。
				postData.id = selectedFirm.id;
				postData.isDefault = 0;
				let res = await updateAudit(postData);
				if (res.code != 200) return uni.$showMsg();
			} 
			// 将当前店铺选中。
			postData.id = item.id;
			postData.isDefault = 1;
			let res = await updateAudit(postData);
			if (res.code != 200) return uni.$showMsg();
			rootState.loading_store.loadingShow = false;
			dispatch('getFirmList');
		}
	},
	getters: {},
}
